package com.wxb.controller;

import com.alibaba.fastjson.JSONObject;
import com.wxb.common.core.utils.StringUtils;
import com.wxb.common.core.web.domain.AjaxResult;
import com.wxb.common.security.utils.SecurityUtils;
import com.wxb.common.util.CharUtil;
import com.wxb.common.util.J2CacheUtils;
import com.wxb.domain.*;
import com.wxb.service.*;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Date 2025-05-30 15:44
 * @Version 1.0
 * @Description
 * @ClassName MallCouponController
 **/
@RestController
@RequestMapping("/coupon")
public class MallCouponController {
    @Autowired
    private IMallUserService apiUserService;
    @Autowired
    private IMallCouponService apiCouponService;
    @Autowired
    private IMallUserCouponService apiUserCouponService;
    @Autowired
    private IMallProductService apiProductService;
    @Autowired
    private IMallCartService apiCartService;

    /**
     * 得到request对象
     */
    @Autowired
    protected HttpServletRequest request;

    /**
     * 获取优惠券列表
     */
    @ApiOperation(value = "获取优惠券列表")
    @PostMapping("/list")
    public Object list() {
        Map<String, Object> param = new HashMap<>();
        param.put("userId", SecurityUtils.getUserId());
        List<MallCouponEntity> couponVos = apiCouponService.queryUserCoupons(param);
        return AjaxResult.success(couponVos);
    }

    /**
     * 根据商品获取可用优惠券列表
     */
    @ApiOperation(value = "根据商品获取可用优惠券列表")
    @PostMapping("/listByGoods")
    public Object listByGoods(@RequestParam(defaultValue = "cart") String type) {
        BigDecimal goodsTotalPrice = new BigDecimal("0.00");
        if ("cart".equals(type)) {
            Map<String, Object> param = new HashMap<>();
            param.put("userId", SecurityUtils.getUserId());
            List<MallCartEntity> cartList = apiCartService.queryList(param);
            //获取购物车统计信息
            for (MallCartEntity cartItem : cartList) {
                if (null != cartItem.getChecked() && 1 == cartItem.getChecked()) {
                    goodsTotalPrice = goodsTotalPrice.add(cartItem.getRetailPrice().multiply(new BigDecimal(cartItem.getNumber())));
                }
            }
        } else { // 是直接购买的
            MallBuyGoodsEntity goodsVo = (MallBuyGoodsEntity) J2CacheUtils.get(J2CacheUtils.SHOP_CACHE_NAME, "goods" + SecurityUtils.getUserId() + "");
            MallProductEntity productInfo = apiProductService.queryObject(goodsVo.getProductId());
            //商品总价
            goodsTotalPrice = productInfo.getRetailPrice().multiply(new BigDecimal(goodsVo.getNumber()));
        }

        // 获取可用优惠券
        Map<String, Object> param = new HashMap<>();
        param.put("userId", SecurityUtils.getUserId());
        param.put("couponStatus", 1);
        List<MallCouponEntity> couponVos = apiCouponService.queryUserCoupons(param);
        List<MallCouponEntity> useCoupons = new ArrayList<>();
        List<MallCouponEntity> notUseCoupons = new ArrayList<>();
        for (MallCouponEntity couponVo : couponVos) {
            if (goodsTotalPrice.compareTo(couponVo.getMinGoodsAmount()) >= 0) { // 可用优惠券
                couponVo.setEnabled(1);
                useCoupons.add(couponVo);
            } else {
                couponVo.setEnabled(0);
                notUseCoupons.add(couponVo);
            }
        }
        useCoupons.addAll(notUseCoupons);
        return AjaxResult.success(useCoupons);
    }

    /**
     * 兑换优惠券
     */
    @ApiOperation(value = "领券优惠券")
    @PostMapping("exchange")
    public Object exchange() {
        JSONObject jsonParam = getJsonRequest();
        String couponNumber = jsonParam.getString("couponNumber");
        if (StringUtils.isEmpty(couponNumber)) {
            return AjaxResult.error("当前优惠码无效");
        }
        //
        Map<String, Object> param = new HashMap<>();
        param.put("couponNumber", couponNumber);
        List<MallUserCouponEntity> couponVos = apiUserCouponService.queryList(param);
        MallUserCouponEntity userCouponVo = null;
        if (null == couponVos || couponVos.size() == 0) {
            return AjaxResult.error("当前优惠码无效");
        }
        userCouponVo = couponVos.get(0);
        if (null != userCouponVo.getUserId() && !userCouponVo.getUserId().equals(0L)) {
            return AjaxResult.error("当前优惠码已经兑换");
        }
        MallCouponEntity couponVo = apiCouponService.queryObject(userCouponVo.getCouponId());
        if (null == couponVo || null == couponVo.getUseEndDate() || couponVo.getUseEndDate().before(new Date())) {
            return AjaxResult.error("当前优惠码已经过期");
        }
        userCouponVo.setUserId(SecurityUtils.getUserId());
        userCouponVo.setAddTime(new Date());
        apiUserCouponService.update(userCouponVo);
        return AjaxResult.success(userCouponVo);
    }

    /**
     * 　　填写手机号码，领券
     */
    @ApiOperation(value = "领券优惠券")
    @PostMapping("newuser")
    public Object newuser(String userMobile) {
        JSONObject jsonParam = getJsonRequest();
        //
        String phone = jsonParam.getString("phone");
        Integer smscode = jsonParam.getInteger("smscode");
        // 校验短信码
        MallSmsLogEntity smsLogVo = apiUserService.querySmsCodeByUserId(SecurityUtils.getUserId());
        if (null != smsLogVo && smsLogVo.getSmsCode() != smscode) {
            return AjaxResult.error("短信校验失败");
        }
        // 更新手机号码
//        if (!StringUtils.isNullOrEmpty(phone)) {
//            if (phone.equals(userMobile)) {
//                loginUser.setMobile(phone);
//                apiUserService.update(loginUser);
//            }
//        }
        // 判断是否是新用户
        if (!StringUtils.isEmpty(userMobile)) {
            return AjaxResult.error("当前优惠券只能新用户领取");
        }
        // 是否领取过了
        Map<String, Object> params = new HashMap<>();
        params.put("userId", SecurityUtils.getUserId());
        params.put("sendType", 4);
        List<MallCouponEntity> couponVos = apiCouponService.queryUserCoupons(params);
        if (null != couponVos && couponVos.size() > 0) {
            return AjaxResult.error("已经领取过，不能重复领取");
        }
        // 领取
        Map<String, Object> couponParam = new HashMap<>();
        couponParam.put("sendType", 4);
        MallCouponEntity newCouponConfig = apiCouponService.queryMaxUserEnableCoupon(couponParam);
        if (null != newCouponConfig) {
            MallUserCouponEntity userCouponVo = new MallUserCouponEntity();
            userCouponVo.setAddTime(new Date());
            userCouponVo.setCouponId(newCouponConfig.getId());
            userCouponVo.setCouponNumber(CharUtil.getRandomString(12));
            userCouponVo.setUserId(SecurityUtils.getUserId());
            apiUserCouponService.save(userCouponVo);
            return AjaxResult.success(userCouponVo);
        } else {
            return AjaxResult.error("领取失败");
        }
    }

    /**
     * 　　转发领取红包
     */
    @ApiOperation(value = "转发领取红包")
    @PostMapping("transActivit")
    public Object transActivit(String sourceKey, Long referrer) {
        JSONObject jsonParam = getJsonRequest();
        // 是否领取过了
        Map<String, Object> params = new HashMap<>();
        params.put("userId", SecurityUtils.getUserId());
        params.put("sendType", 2);
        params.put("sourceKey", sourceKey);
        List<MallCouponEntity> couponVos = apiCouponService.queryUserCoupons(params);
        if (null != couponVos && couponVos.size() > 0) {
            return AjaxResult.warn( "已经领取过", couponVos);
        }
        // 领取
        Map<String, Object> couponParam = new HashMap<>();
        couponParam.put("sendType", 2);
        MallCouponEntity newCouponConfig = apiCouponService.queryMaxUserEnableCoupon(couponParam);
        if (null != newCouponConfig) {
            MallUserCouponEntity userCouponVo = new MallUserCouponEntity();
            userCouponVo.setAddTime(new Date());
            userCouponVo.setCouponId(newCouponConfig.getId());
            userCouponVo.setCouponNumber(CharUtil.getRandomString(12));
            userCouponVo.setUserId(SecurityUtils.getUserId());
            userCouponVo.setSourceKey(sourceKey);
            userCouponVo.setReferrer(referrer);
            apiUserCouponService.save(userCouponVo);
            //
            List<MallUserCouponEntity> userCouponVos = new ArrayList<>();
            userCouponVos.add(userCouponVo);
            //
            params = new HashMap<>();
            params.put("userId", SecurityUtils.getUserId());
            params.put("sendType", 2);
            params.put("sourceKey", sourceKey);
            couponVos = apiCouponService.queryUserCoupons(params);
            return AjaxResult.success(couponVos);
        } else {
            return AjaxResult.error("领取失败");
        }
    }

    public JSONObject getJsonRequest() {
        JSONObject result = null;
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = request.getReader();) {
            char[] buff = new char[1024];
            int len;
            while ((len = reader.read(buff)) != -1) {
                sb.append(buff, 0, len);
            }
            result = JSONObject.parseObject(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }
}
